package be.jaisy.adapter.hibernate.extender.internal;

import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleEvent;
import org.osgi.framework.BundleListener;
import org.osgi.service.component.ComponentContext;


/**
 * @author Stany Blanvalet
 */
public class HibernateExtenderListener implements BundleListener {

	private BundleContext context;

	private HibernateExtenderRegistry domainModelExtenderRegistry;
	
	public HibernateExtenderListener() {
		super();
		domainModelExtenderRegistry = new HibernateExtenderRegistry();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.osgi.framework.BundleListener#bundleChanged(org.osgi.framework.BundleEvent)
	 */
	public void bundleChanged(BundleEvent event) {		
		//Activator.logDebug(this.getClass(),"received bundleEvent ["+event.getType()+"] for ["+event.getBundle().getBundleId()+"].["+ event.getBundle().getSymbolicName()+"].");
		switch (event.getType()) {
		case BundleEvent.STARTED:
			domainModelExtenderRegistry.register(event.getBundle());
			break;

		case BundleEvent.STOPPED:
			domainModelExtenderRegistry.unregister(event.getBundle());
			break;
		}
	}

	protected void activate(ComponentContext cc) {
		//Activator.logDebug(this.getClass(),"activation started.");
		this.context = cc.getBundleContext();
		this.context.addBundleListener(this);
		for (Bundle bundle : context.getBundles()) {
			domainModelExtenderRegistry.register(bundle);
		}
	}

	protected void deactivate(ComponentContext context) throws Exception {
		//Activator.logDebug(this.getClass(),"deactivation started.");
		domainModelExtenderRegistry.close();
	}	
}
